using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Colorprj.Common;
using Colorprj.Masters ;
namespace Colorprj
{
    public partial class frmChallan : Form
    {
        //BindingSource parentBS = new BindingSource();
        //BindingSource childBS = new BindingSource();
        //BindingSource filteredChildBS = new BindingSource();
        ProductMasterData pmd = new ProductMasterData();
        Colorprj.Masters.SubProductManager spm = new Colorprj.Masters.SubProductManager();  
        Challan.ChallanManager cm = new Colorprj.Challan.ChallanManager();
        BuyerManager bm = new BuyerManager();
        SalesManManager oSalesManManager = new SalesManManager();  

        public frmChallan()
        {
            InitializeComponent();
        }

        private void frmChallan_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'colorPrjBuyer.Buyer' table. You can move, or remove it, as needed.
            //this.buyerTableAdapter.Fill(this.colorPrjBuyer.Buyer);
            cboParty.DataSource = bm.GetAllBuyers(1).Tables[0] ;
            cboParty.DisplayMember = "BuyerName";
            cboParty.ValueMember = "BuyerId"; 

            SubProduct.DataSource = spm.GetAllProducts().Tables[0];
            SubProduct.DisplayMember = "subProductName";
            SubProduct.ValueMember = "subProductId";

            cboSalesMan.DataSource = oSalesManManager.GetAllSalesMan().Tables[0];
            cboSalesMan.DisplayMember = "SalesManName";
            cboSalesMan.ValueMember = "SalesManId"; 


            txtChallanNo.Text = cm.GetNextChallanNo();  

        }

        private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //if (this.dataGridView2.CurrentCell.ColumnIndex == SubProduct.Index)
            //{
            //    DataGridViewComboBoxEditingControl control = e.Control as DataGridViewComboBoxEditingControl;
            //    BindingSource bs = control.DataSource as BindingSource;
            //    if (bs != null)
            //    {
            //        // set the filteredChildBS as the DataSource of the editing control
            //        (e.Control as ComboBox).DataSource = filteredChildBS;

            //        object regionvalue = this.dataGridView2.Rows[this.dataGridView2.CurrentCell.RowIndex].Cells[Product.Index].Value;
            //        if (regionvalue == DBNull.Value || regionvalue == null)
            //        {
            //            filteredChildBS.Filter = "Productid=-1";
            //        }
            //        else
            //        {
            //            filteredChildBS.Filter = "Productid=" + regionvalue.ToString();
            //        }
            //        // set the SelectedValue property of the editing control
            //        if (this.dataGridView2.CurrentCell.Value != DBNull.Value && this.dataGridView2.CurrentCell.Value != null)
            //        {
            //            control.SelectedValue = this.dataGridView2.CurrentCell.Value;
            //        }
            //    }
            //}

        }

        private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {

           if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {

                int myval = Convert.ToInt16(this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
                this.dataGridView2.Rows[e.RowIndex].Cells["Rate"].Value = cm.GetSubProductById(myval).SaleRate;
                this.dataGridView2.Rows[e.RowIndex].Cells["Stock"].Value = cm.GetSubProductById(myval).Stock;

            }

          
        }
        private void dataGridView2_RowLeave(object sender, DataGridViewCellEventArgs e)
        {


            if (dataGridView2[0, e.RowIndex].Value != null 
                && dataGridView2[1, e.RowIndex].Value != null 
                && Convert.ToInt16(dataGridView2[2, e.RowIndex].Value) != 0 
                && Convert.ToDecimal(dataGridView2[3, e.RowIndex].Value) != 0)
            {

                // string aa = dataGridView2[1, e.RowIndex].Value.ToString() ;
                dataGridView2.AllowUserToAddRows = true;

            }
            else { 
                if (dataGridView2.RowCount>1) dataGridView2.AllowUserToAddRows = false; 
            
            
            }
        }

        private void dataGridView2_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);

            if (dataGridView2.Rows.Count > 0)
                txtTotal.Text = Total().ToString("F2");

        }
        private double Total()
        {
            double tot = 0;
            int i = 0;
            for (i = 0; i < dataGridView2.Rows.Count; i++)
            {
                tot = tot + Convert.ToDouble(dataGridView2.Rows[i].Cells["Amount"].Value);
            }
            return tot;
        }
        private void dataGridView2_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2.Rows[e.RowIndex].ErrorText = String.Empty;

        }
        private void dataGridView2_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            string headerText = dataGridView2.Columns[e.ColumnIndex].HeaderText;


            if (headerText.Equals("Sub-prd"))
            {
                if (string.IsNullOrEmpty(e.FormattedValue.ToString()))
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                        "Sub Product must not be empty";
                    e.Cancel = true;
                }

                if (IsDuplicate(e.FormattedValue.ToString()) && dataGridView2.Rows[e.RowIndex].Cells["ChallanDetId"].Value == null)
                {
                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                "Sub Product Allready Exist";
                    e.Cancel = true;

                }
             
            }
            if (headerText.Equals("Qty"))
            {
                double curQty = Utility.getDblVal(e.FormattedValue.ToString());
                double OldQty = Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["OldQty"].Value);
                double StockQty = Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["Stock"].Value);
                if (curQty > OldQty + StockQty)
                {

                    dataGridView2.Rows[e.RowIndex].ErrorText =
                                    "Qty is greater then avialable qty in stock";
                    e.Cancel = true;
                }
            }
        }
        private bool IsDuplicate(string spvalue)
        {
            bool retval = false;
            int rowCnt = 0;
            System.Collections.Hashtable hash = new System.Collections.Hashtable();

            for (rowCnt = 0; rowCnt < dataGridView2.RowCount - 1; rowCnt++)
            {
                String SubproductId = dataGridView2["Subproduct", rowCnt].FormattedValue.ToString();
                if (hash.Contains(spvalue))
                {
                    retval = true;
                    break;
                }
                else
                {
                    hash.Add(SubproductId, SubproductId);
                }

            }
            return retval;
        }

        private Challan.ChallanHeadEntity getFormData()
        {
            Challan.ChallanHeadEntity phEntity = new Colorprj.Challan.ChallanHeadEntity();
            phEntity.BuyerId  = Convert.ToInt16(cboParty.SelectedValue);
            phEntity.ChallanNo = txtChallanNo.Text;
            phEntity.ChallanDate = dtChallanDate.Value;

            phEntity.Mop = txtMop.Text;
            phEntity.TotalAmount = Utility.getDblVal(txtTotal.Text);

            phEntity.SalesManId  = Convert.ToInt16(cboSalesMan.SelectedValue);

            if (!txtChallanHeadId.Text.Trim().Equals(""))
            {
                phEntity.ChallanHeadId = Convert.ToInt16(txtChallanHeadId.Text);
            }

            List<Challan.ChallanDetailEntity> pdEntityList = new List<Colorprj.Challan.ChallanDetailEntity>();
            int rowCnt = 0;
            for (rowCnt = 0; rowCnt < dataGridView2.RowCount; rowCnt++)
            {
                //int prdId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                //int subPrdId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                //int qty = Convert.ToInt16(dataGridView2["Qty", rowCnt].Value);
                //if (qty > 0)
                //{
                Challan.ChallanDetailEntity pdEntity = new Colorprj.Challan.ChallanDetailEntity();
                //pdEntity.ProductId = Convert.ToInt16(dataGridView2["Product", rowCnt].Value);
                pdEntity.Qty = Convert.ToDouble(dataGridView2["Qty", rowCnt].Value);
                pdEntity.OldQty = Convert.ToDouble(dataGridView2["OldQty", rowCnt].Value);
                pdEntity.Rate = Convert.ToDouble(dataGridView2["Rate", rowCnt].Value);
                pdEntity.Amount = Convert.ToDouble(dataGridView2["Amount", rowCnt].Value);
                pdEntity.SubproductId = Convert.ToInt16(dataGridView2["Subproduct", rowCnt].Value);
                pdEntity.ChallanDetailId = Convert.ToInt16(dataGridView2["ChallanDetId", rowCnt].Value);
                if (pdEntity.Qty > 0 || pdEntity.ChallanDetailId > 0)
                {
                    pdEntityList.Add(pdEntity);
                }
                //}
            }
            phEntity.ChallanDetailList = pdEntityList;
            return phEntity;
        }


        private void btnSave_Click(object sender, EventArgs e)
        {
            Challan.ChallanHeadEntity  phEntity = getFormData();
              if (phEntity.BuyerId == 0) {
                MessageBox.Show("Please Select Buyer");
                return;
            
            }
            if (phEntity.SalesManId  == 0)
            {
                MessageBox.Show("Please Select SalesMan");
                return;

            }
            if (phEntity.ChallanDetailList.Count == 0) {
                MessageBox.Show("Please add some detail data");
                return;
            
            }
            Challan.ChallanManager cm = new Challan.ChallanManager();
            cm.AddChallan(phEntity);
            
            DialogResult result =  MessageBox.Show("challan Saved ! do you want to print", "", MessageBoxButtons.YesNo);   

			if (result == System.Windows.Forms.DialogResult.Yes)
			{
                frmrptChallan frmchPrint = new frmrptChallan();
                frmchPrint.challanNo = phEntity.ChallanNo;//cm.GetLastChallanNo() ;
                frmchPrint.ShowDialog();  

			}


            ClearForm(this.Controls);
        }
        //private void ClearForm()
        //{

        //    btnSave.Enabled = true;
        //    btnUpdate.Enabled = false;
        //    //this.dataGridView2.Rows.Clear();
        //    txtChallanHeadId.Text = "";
        //    txtTotal.Text = "";
        //    //txtPurNo.Text = "";
        //    // cboParty.SelectedIndex = -1;
        //    //foreach (Control c in Form.ControlCollection )
        //    //{
        //    //    if (c is TextBox)
        //    //    {
        //    //        ((TextBox)c).Text = ((TextBox)c).Text + ((TextBox)c).Name + "\n";
        //    //    }
        //    //}
        //    Control.ControlCollection coll = this.Controls;
        //    //List<ComboBox> list33 = GetControlsOfType<ComboBox>(coll);
        //    foreach (Control c in coll)
        //    {
        //        //if (c != null)
        //        //    Console.WriteLine(c.Text, "Index numb: " + coll.GetChildIndex(c, false));
        //        if (c is TextBox) c.Text = string.Empty;
        //        if (c is DataGridView) { ((DataGridView)c).Rows.Clear(); }
        //        if (c is ComboBox)
        //        {
        //            ((ComboBox)c).SelectedIndex = -1;
        //        }
        //    }





        //}

        public void ClearForm(Control.ControlCollection coll)
        {
            // Control.ControlCollection coll = this.Controls;
            foreach (Control c in coll)
            {
                if (c.HasChildren) ClearForm(c.Controls);
                if (c is TextBox) c.Text = string.Empty;
                if (c is DataGridView) { ((DataGridView)c).Rows.Clear(); }
                if (c is ComboBox)
                {
                    ((ComboBox)c).SelectedIndex = -1;
                }
            }
            txtChallanNo.Text = cm.GetNextChallanNo();
            btnSave.Enabled = true;
            btnUpdate.Enabled = false; 
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            frmChallanSearch ps = new frmChallanSearch();
            Challan.ChallanManager cm = new Colorprj.Challan.ChallanManager();  
            if (ps.ShowDialog() == DialogResult.OK)
            {

                int ChallanId = Convert.ToInt16(ps.ItemToRead);


                Challan.ChallanHeadEntity phEntity = cm.GetChallan(ChallanId);
                txtChallanHeadId.Text = ChallanId.ToString();
                txtChallanNo.Text = phEntity.ChallanNo;
                dtChallanDate.Value = phEntity.ChallanDate;
                cboParty.SelectedValue = phEntity.BuyerId ;
                txtTotal.Text = phEntity.TotalAmount.ToString();
                txtMop.Text = phEntity.Mop.ToString();
                cboSalesMan.SelectedValue = phEntity.SalesManId; 
                if (phEntity.InvoiceId > 0 || phEntity.Printed)
                {

                    dataGridView2.Enabled = false;
                    btnUpdate.Enabled = false;
                }
                else {
                   
                    btnUpdate.Enabled = true;
                    dataGridView2.Enabled = true ;
                }
                btnSave.Enabled = false;
                dataGridView2.RowCount = phEntity.ChallanDetailList.Count + 1;
                int row = 0;
                foreach (Challan.ChallanDetailEntity pdEntity in phEntity.ChallanDetailList)
                {

                    //dataGridView2["Product", row].Value = pdEntity.ProductId;
                    dataGridView2["SubProduct", row].Value = pdEntity.SubproductId;
                    dataGridView2["Qty", row].Value = pdEntity.Qty;
                    dataGridView2["Rate", row].Value = pdEntity.Rate;
                    dataGridView2["Amount", row].Value = pdEntity.Amount;
                    dataGridView2["ChallanDetId", row].Value = pdEntity.ChallanDetailId;
                    dataGridView2["OldQty", row].Value = pdEntity.Qty;
                    row++;

                }

              
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Challan.ChallanHeadEntity phEntity = getFormData();
            Challan.ChallanManager pm = new Colorprj.Challan.ChallanManager();
            pm.UpdChallan(phEntity);
            ClearForm(this.Controls);
        }

        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            ClearForm(this.Controls);
        }

        private void dataGridView2_CellLeave(object sender, DataGridViewCellEventArgs e)
        {
            dataGridView2["Amount", e.RowIndex].Value = Convert.ToDecimal(dataGridView2["Qty", e.RowIndex].Value) * Convert.ToDecimal(dataGridView2["Rate", e.RowIndex].Value);
            dataGridView2.AllowUserToAddRows = true;
        }

        private void dataGridView2_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            if (Utility.getDblVal(dataGridView2.Rows[e.RowIndex].Cells["Qty"].Value) <= 0 && dataGridView2.Rows[e.RowIndex].Cells["ChallanDetId"].Value == null)
            {
                dataGridView2.Rows[e.RowIndex].ErrorText =
                       "Qty must not be 0";
                e.Cancel = true;
            } 
        }

  

      

     

       

    }
}